package com.lkd.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.RegionDto;
import com.lkd.entity.Node;
import com.lkd.entity.Region;
import com.lkd.mapper.NodeMapper;
import com.lkd.mapper.RegionMapper;
import com.lkd.service.IRegionService;
import com.lkd.vo.PageBean;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 运营区域 服务实现类
 * </p>
 *
 * @author xiaotao
 * @since 2025-10-11
 */
@Service
@RequiredArgsConstructor
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements IRegionService {
    /**
     * 区域搜索
     *
     * @param regionDto
     * @return
     */
    private final NodeMapper nodeMapper;

    @Override
    public PageBean<Region> search(RegionDto regionDto) {
        //1.设置分页参数
        Page<Region> regionPage = new Page<>(regionDto.getPageIndex(), regionDto.getPageSize());

        //2.设置业务参数
        LambdaQueryWrapper<Region> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(regionDto.getName()), Region::getName, regionDto.getName());

        //3.调用分页查询
        Page<Region> page = this.page(regionPage, wrapper);
        List<Region> regionList = page.getRecords().stream().map(region -> {
            Long nodeCount = nodeMapper.selectCount(new LambdaQueryWrapper<Node>().eq(Node::getRegionId, region.getId()));
            region.setNodeCount(nodeCount);
            return region;
        }).collect(Collectors.toList());

        //4.返回封装结果
        return new PageBean<>((int)page.getCurrent(), (int)page.getSize(), page.getPages(), page.getTotal(), regionList);
    }
}
